/*
** string_list.c for zappy in /home/guidet_m/TECK2/projets/zappy/server_zappy
** 
** Made by michael guidet
** Login   <guidet_m@epitech.net>
** 
** Started on  Tue Jul  5 10:23:03 2011 michael guidet
** Last update Tue Jul  5 13:23:25 2011 michael guidet
*/

#include "server.h"

void		add_string_to_list(t_string_list **begin, char *str)
{
  unsigned int	len;
  t_string_list	*tmp;
  t_string_list	*new;

  for (len = 0; len <= strlen(str) / BUF_SIZE; len++)
    {
      for (tmp = *begin; tmp; tmp = tmp->next)
	if (tmp->next == NULL)
	  break;
      new = x_null(NULL, malloc(sizeof(*new)), "malloc");
      if (tmp != NULL)
	tmp->next = new;
      else
	*begin = new;
      new->next = NULL;
      memset(new->str, 0, BUF_SIZE + 1);
      x_null(NULL, strncpy(new->str, &str[len * BUF_SIZE], BUF_SIZE),
	     "strcpy");
    }
}

char		*clean_string_list(t_string_list **begin)
{
  t_string_list	*to_free;
  t_string_list	*tmp;
  char		*result;
  unsigned int	len;

  len = BUF_SIZE;
  result = x_null(NULL, malloc(sizeof(*result) * (len + 1)), "malloc");
  memset(result, 0, BUF_SIZE + 1);
  to_free = NULL;
  for (tmp = *begin; tmp; tmp = tmp->next)
    {
      if (to_free)
	free(to_free);
      x_null(NULL, strcat(result, tmp->str), "strcat");
      len += BUF_SIZE;
      result = x_null(NULL, realloc(result, sizeof(*result)
				* (len + 1)), "malloc");
      memset(&result[len - BUF_SIZE], 0, BUF_SIZE + 1);
      to_free = tmp;
    }
  if (to_free)
    free(to_free);
  *begin = NULL;
  return (result);
}
